//
//  LGReusable.swift
//  swiftLingo
//
//  Created by lingo on 2017/11/7.
//  Copyright © 2017年 livefor. All rights reserved.
//

import UIKit

protocol LGReusable {
    static var reuseIdentifier: String { get }
}

extension LGReusable {
    static var reuseIdentifier: String {
        return String(describing: self)
    }
}

extension UITableView {
    //1. final 不需要集成或者重写
    //2. <T:UITableView> 泛型约束,必须是UITableView类型
    //3. T: LGReusable 需要遵循LGReusable协议
    final func registerReusable<T:UITableViewCell>(cellType:T.Type) where T: LGReusable{
        self.register(cellType.self, forCellReuseIdentifier: cellType.reuseIdentifier)
    }
    
    final func dequeueReusableCell<T:UITableViewCell>(withCellType cellType:T.Type = T.self, indexPath:IndexPath)->T where T:LGReusable{
        guard let cell = self.dequeueReusableCell(withIdentifier: cellType.reuseIdentifier, for: indexPath) as? T else{
            fatalError("UITableViewCell重用失败")
        }
        return cell
    }
}

extension UICollectionView {
    final func registerReusable<T:UICollectionViewCell>(cellType:T.Type) where T:LGReusable{
        self.register(cellType.self, forCellWithReuseIdentifier: cellType.reuseIdentifier)
    }
    
    final func dequeueReusableCell<T:UICollectionViewCell>(withCellType cellType:T.Type = T.self, indexPath:IndexPath)->T where T:LGReusable{
        guard let cell = self.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath) as? T else{
            fatalError("UICollectionViewCell重用失败")
        }
        return cell
    }
    
 //   open func register(_ cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String)
    
}

